package com.hibiscusking.org.service.impl;

import com.hibiscusking.basic.service.impl.BaseServiceImpl;
import com.hibiscusking.org.domain.Department;
import com.hibiscusking.org.mapper.DepartmentMapper;
import com.hibiscusking.org.service.DeparmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DeparmentServiceImpl extends BaseServiceImpl<Department> implements DeparmentService {
    @Autowired
    private DepartmentMapper departmentMapper;





    @Override
    public List<Department> departTree() {
//        List<Department> all = departmentMapper.findAll();
//        List<Department> result = new ArrayList<>();
//        for (Department department : all) {
//            if (department.getParentId() == null) {
//                result.add(department);
//            } else {
//                for (Department dept : all) {
//                    if (dept.getId().equals(department.getParentId())) {
//                        List<Department> children = dept.getChildren();
//                        children.add(dept);
//                        break;
//                    }
//                    }
//                }
//            }
//        return result;
//    }
        List<Department> allDepts = departmentMapper.findAll();
        List<Department> result = new ArrayList<>();
        for (Department dept : allDepts) {
            if (null == dept.getParentId()) {
                result.add(dept);
            } else {
                for (Department parent : allDepts) {
                    if (parent.getId().equals(dept.getParentId())) {
                        List<Department> children = parent.getChildren();
                        children.add(dept);
                        break;
                    }
                }
            }
        }
        return result;
    }
}
